<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\DownloadTemplate;
use App\Admin\Forms\PackageImport;
use App\Admin\Forms\PackageUsedImport;
use App\Admin\Repositories\CarPackageOrder;
use App\Admin\Services\AdminUserService;
use App\Models\Brand;
use App\Models\Car;
use App\Models\CarPackage;
use App\Models\CarPackageCategory;
use App\Models\CarPackageOrderAttr;
use App\Models\Store;
use App\Services\LifeCycle\OrderService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\OperationLog\Models\OperationLog;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Modal;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CarPackageOrderController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(CarPackageOrder::with(['brand', 'category', 'store', 'user', 'package']), function (Grid $grid) {
            $grid->tools('<a class="btn btn-primary" href="car-package-order-examine">用户套餐列表</a>');

            $package_id = AdminUserService::permissionOrders(Auth::guard('admin')->user()->username);

            if ($package_id) {
                $grid->model()->whereIn('package_id', $package_id);
            }

            $grid->column('id')->sortable();

            if ($package_id && $package_id[0] == PACKAGE_ID_BJQ) {
                $grid->column('car_number');
            } else {
                $grid->column('user_name');
            }

            $grid->column('user_phone');
            $grid->column('package.title', admin_trans('car-package-order.fields.package_title'));
            if ($package_id && $package_id[0] == PACKAGE_ID_BJQ) {
                $grid->column('coupon_attr_number');
            }
            $grid->column('status')->using(admin_trans('car-package-order.options.status'))->badge([
                0 => 'primary',
                1 => 'success',
                2 => 'danger',
                3 => 'success',
                4 => 'danger',
                5 => 'danger'
            ]);
            $grid->column('user_id', admin_trans('car-package-order.fields.user_status'))->display(function ($user_id) {
                return $user_id ? '已领取' : '未领取';
            })->badge([
                '0' => 'danger',
                'default' => 'success'
            ]);
            $grid->column('created_at')->sortable();
            $grid->export();

            $grid->model()->orderBy('id', 'desc');

            $grid->export()->rows(function ($rows) {
                foreach ($rows as $index => &$row) {
                    $row['status'] = OrderService::orderStatusTitle($row['status']);
                }

                return $rows;
            });

            $grid->filter(function (Grid\Filter $filter) use ($package_id) {
                $filter->equal('id');
                $filter->like('user.phone', admin_trans('car-package-order.fields.phone'));

                if ($package_id && $package_id[0] == PACKAGE_ID_BJQ) {
                    $filter->like('car_number');
                } else {
                    $filter->like('user_name');
                }

                if ($package_id) {
                    $package_one = CarPackage::where('status', DEFAULT_STATUS_SUCCESS)->where('id', $package_id)->first();
                    $category = CarPackageCategory::where('status', DEFAULT_STATUS_SUCCESS)->where('id', $package_one->category->id)->pluck('title', 'id');
                } else {
                    $category = CarPackageCategory::where('status', DEFAULT_STATUS_SUCCESS)->pluck('title', 'id');
                }

                $filter->equal('category_id')->select($category);
                $filter->equal('status')->select(admin_trans('car-package-order.options.status'));
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append("<a href='/admin/car-package-order-attr?order_id={$actions->getKey()}'>查看用户套餐</a>");
                $actions->append("<a href='/admin/car-package-used-log?order_id={$actions->getKey()}'>查看使用列表</a>");
            });

            $grid->disableDeleteButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, CarPackageOrder::with(['brand', 'category', 'store', 'package']), function (Show $show) {
            $show->field('id');
            $show->field('status')->using(admin_trans('car-package-order.options.status'));
            $show->field('category.title', admin_trans('car-package-order.fields.category_id'));
            $show->field('user_name');
            $show->field('user_phone');
            $show->field('code_url')->image();
            $show->field('code_number');
            $show->field('created_at');
            $show->field('updated_at');

            $show->panel()->tools(function ($tools) {
                $tools->disableDelete();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(CarPackageOrder::with(['user']), function (Form $form) {

            $package_id = AdminUserService::permissionOrders(Auth::guard('admin')->user()->username);

            if ($package_id) {
                $package = CarPackage::where('status', DEFAULT_STATUS_SUCCESS)->where('id', $package_id)->pluck('title', 'id');
                $package_one = CarPackage::where('status', DEFAULT_STATUS_SUCCESS)->where('id', $package_id)->first();
                $category = CarPackageCategory::where('status', DEFAULT_STATUS_SUCCESS)->where('id', $package_one->category->id)->pluck('title', 'id');
            } else {
                $package = CarPackage::where('status', DEFAULT_STATUS_SUCCESS)->pluck('title', 'id');
                $category = CarPackageCategory::where('status', DEFAULT_STATUS_SUCCESS)->pluck('title', 'id');
            }

            $form->display('id');
            $form->select('category_id')
                ->options($category)
                ->load('package_id', 'category-package')
                ->required();

            $form->select('package_id')
                ->options($package)
                ->load('user_car_id', 'package-car')
                ->required();

            if ($package_id && $package_id[0] == PACKAGE_ID_BJQ) {
                $form->text('car_number')->required();
                $form->text('user_phone')->required();
                $form->number('coupon_attr_number')->default(1)->attribute('max', 5)->help('最多发放5张代金券！')->required();
            } else {
                $form->select('user_car_id')
                    ->options(Car::where('brand_id', 1)->where('status', DEFAULT_STATUS_SUCCESS)->pluck('title', 'id'))
                    ->required();
                $form->text('user_name')->required();
                $form->text('user_phone')->required();
                $form->text('user_id_card')->required();
                $form->text('car_frame')->required();
            }
            $form->select('status')->options(admin_trans('car-package-order.options.status'))->required();

            $form->hidden('code_number');
            $form->hidden('code_url');
            $form->display('created_at');
            $form->display('updated_at');

            $form->tools(function (Form\Tools $tools) {
                $tools->disableDelete();
            });

            $form->saving(function ($form) {
                if ($form->package_id == PACKAGE_ID_BJQ) {
                    $order = \App\Models\CarPackageOrder::where('package_id', $form->package_id)->where('car_number', $form->car_number)->first();

                    if (!$order) {
                        $order = \App\Models\CarPackageOrder::where('package_id', $form->package_id)->where('user_phone', $form->user_phone)->first();

                        if ($order) {
                            $count = CarPackageOrderAttr::where('order_id', $order->id)->count();

                            if ($count <= 5) {
                                if ($form->coupon_attr_number > 5) {
                                    return $form->response()->error("该用户已领{$count}张券，每人最多可领5张！");
                                }
                            }
                        }
                    } else {
                        $count = CarPackageOrderAttr::where('order_id', $order->id)->count();

                        if ($count <= 5) {
                            if ($form->coupon_attr_number > 5) {
                                return $form->response()->error("该用户已领{$count}张券，每人最多可领5张！");
                            }
                        }

                        if ($form->coupon_attr_number < $order->coupon_attr_number) {
                            return $form->response()->error("优惠券数量只可加不能减！");
                        }
                    }
                }

                $form->model()->admin_user_id = Auth::guard('admin')->user()->id;
                $form->model()->admin_user_ip = getRealIp();
            });

            $form->saved(function (Form $form) {
                $order = \App\Models\CarPackageOrder::find($form->getKey());
                if ($order->package_id == PACKAGE_ID_BJQ) {
                    $count = CarPackageOrderAttr::where('order_id', $order->id)->count();
                    $package_attr = json_decode($order->package->attrs, true);

                    if ($package_attr) {
                        for ($i = 1; $i <= ($order->coupon_attr_number-$count); $i++) {
                            foreach ($package_attr as $key => $value) {
                                CarPackageOrderAttr::create([
                                    'user_id' => $order->user_id,
                                    'package_id' => $order->package->id,
                                    'order_id' => $order->id,
                                    'package_title' => $order->package->title,
                                    'attr_title' => $value['content'],
                                    'price' => $value['price'],
                                    'usable_number' => $value['count'],
                                    'total_number' => $value['count'],
                                    'used_number' => 0,
                                    'admin_user_id' => Auth::guard('admin')->user()->id,
                                    'admin_user_ip' => getRealIp()
                                ]);
                            }
                        }
                    }
                }
            });
        });
    }

    public function packageCar(Request $request)
    {
        $package_id = $request->get('q');

        $package = CarPackage::find($package_id);
        $car_ids = json_decode($package->category->car_ids, true);

        return Car::whereIn('id', $car_ids)->get(['id', DB::raw('title as text')]);
    }

    public function categoryPackage(Request $request)
    {
        $category_id = $request->get('q');

        return CarPackage::where('category_id', $category_id)->get(['id', DB::raw('title as text')]);
    }
}
